import { FieldSelect, ProFieldFC, isUrl } from '@ant-design/pro-components';
import FieldHOC from '@ant-design/pro-field/es/FieldHOC';
import { useNavigate } from '@umijs/max';
import { Badge, Typography } from 'antd';
import lodash from 'lodash';
import React from 'react';

export type ModelShowValueType = {
  id?: string;
  code?: string;
  name?: string;
};

const getText = (prefixValue?: string, labelValue?: string) => {
  if (!prefixValue && !labelValue) {
    return '-';
  }
  if (!prefixValue) {
    return labelValue;
  }
  if (!labelValue) {
    return prefixValue;
  }

  return `[${prefixValue}] ${labelValue}`;
};

const voFieldMark = 'Vo';

const FieldSfwModel: ProFieldFC<{
  text: ModelShowValueType | any;
}> = (props) => {
  const { text, mode, fieldProps, proFieldKey } = props;
  const isVo = lodash.endsWith(proFieldKey as string, voFieldMark);
  const defaultDomType = isVo ? 'text' : 'link';
  const defaultLabel = isVo ? 'label' : 'name';
  const { domType, fieldNames, ellipsis, href, ...restFiledProps } = fieldProps;
  const { label, prefix = 'code' } = fieldNames || {};
  const navigate = useNavigate();

  if (mode === 'read') {
    // @ts-ignore
    let child = getText(text[prefix], text[label || defaultLabel]);

    const tooltip = {
      title: child,
    };
    return (domType || defaultDomType) === 'text' ? (
      <Typography.Text ellipsis={{ tooltip, ...ellipsis }} {...restFiledProps}>
        {isVo && !lodash.isEmpty(text.status) ? (
          <Badge status={text.status as any} text={child} />
        ) : (
          child
        )}
      </Typography.Text>
    ) : (
      <Typography.Text
        ellipsis={{ tooltip, ...ellipsis }}
        style={{
          color: 'inherit',
          textDecoration: 'inherit',
          outline: 'inherit',
        }}
      >
        <Typography.Link
          href={!href ? null : isUrl(href) ? href : null}
          onClick={
            !href
              ? null
              : isUrl(href)
              ? null
              : () => {
                  navigate(href);
                }
          }
          // target="_blank"
          {...restFiledProps}
        >
          {child}
        </Typography.Link>
      </Typography.Text>
    );
  }

  if (mode === 'edit' || mode === 'update') {
    return (
      <FieldHOC isLight={props.light}>
        <FieldSelect
          debounceTime={200}
          {...props}
          fieldProps={{
            showSearch: true,
            labelInValue: true,
            ...props.fieldProps,
          }}
        />
      </FieldHOC>
    );
  }

  return <Typography.Text type={'warning'}>UNKNOWN</Typography.Text>;
};

export default FieldSfwModel;
